package vip.aster.framework.license.core;

import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import vip.aster.common.config.AsterConfig;

import java.io.File;

/**
 * 在项目启动时安装证书
 *
 * @author Aster
 * @since 2024/12/30 16:35
 */
@Slf4j
@Component
public class LicenseCheckListener implements ApplicationListener<ContextRefreshedEvent> {

    /**
     * 是否开启证书校验
     */
    @Value("${license.enabled}")
    private Boolean enabled;

    /**
     * 证书subject
     */
    @Value("${license.subject}")
    private String subject;

    /**
     * 公钥别称
     */
    @Value("${license.publicAlias}")
    private String publicAlias;

    /**
     * 访问公钥库的密码
     */
    @Value("${license.storePass}")
    private String storePass;

    /**
     * 证书生成路径
     */
    @Value("${license.licensePath}")
    private String licensePath;

    /**
     * 密钥库存储路径
     */
    @Value("${license.publicKeysStorePath}")
    private String publicKeysStorePath;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 没开启校验直接跳过
        if (!enabled) {
            return;
        }
        // root application context 没有parent
        ApplicationContext context = event.getApplicationContext().getParent();
        if (context == null && StrUtil.isNotBlank(licensePath)) {
            // 检查 licensePath 文件是否存在
            File licenseFile = new File(licensePath);
            if (!licenseFile.exists()) {
                log.error("证书文件不存在: {}", licensePath);
                return;
            }

            log.info("++++++++ 开始安装证书 ++++++++");

            LicenseVerifyParam param = new LicenseVerifyParam();
            param.setSubject(subject);
            param.setPublicAlias(publicAlias);
            param.setStorePass(storePass);
            param.setLicensePath(licensePath);
            param.setPublicKeysStorePath(publicKeysStorePath);

            LicenseVerify licenseVerify = new LicenseVerify();
            // 安装证书
            licenseVerify.install(param);

            log.info("++++++++ 证书安装结束 ++++++++");
        }
    }
}
